<?php

namespace app\admin\controller\qingdongams\jigoustatistic;


use addons\qingdongams\model\Form;
use addons\qingdongams\model\Receivables;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use addons\qingdongams\model\Contract as ContractModel;
use addons\qingdongams\model\Staff;
use fast\Tree;
use think\Config;

/**
 * 订单分析
 */
class Contract extends Backend
{
    public function _initialize()
    {
        parent::_initialize();

        $childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthGroup::where('id', 'in', $childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupList = [];
        if ($this->auth->isSuperAdmin()) {
            $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->auth->getGroups();
            $groupIds = [];
            foreach ($groups as $m => $n) {
                if (in_array($n['id'], $groupIds) || in_array($n['pid'], $groupIds)) {
                    continue;
                }
                $groupList = array_merge($groupList, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
                foreach ($groupList as $index => $item) {
                    $groupIds[] = $item['id'];
                }
            }
        }
        $this->assign('groupdata',$groupList);
    }

    /**
     * 新增订单
     */
    public function newadd()
    {

        $type=input('type','bar');//bar 柱状图 pie 饼状图
        $row = input('row/a');
        $year = $row['year'] ?? date('Y');
        $betweentime = [date('Y-m-d 00:00:00',strtotime($year . '-01-01')), date('Y-m-d 23:59:59',strtotime($year . '-12-31') + 86400 - 1)];
        $between = [strtotime($year . '-01-01'), strtotime($year . '-12-31') + 86400 - 1];
        $lastbetweentime = [date('Y-m-d 00:00:00',strtotime(($year-1) . '-01-01')), date('Y-m-d 23:59:59',strtotime(($year-1) . '-12-31') + 86400 - 1)];
        $lastbetween = [strtotime(($year-1) . '-01-01'), strtotime(($year-1) . '-12-31') + 86400 - 1];

        $group_id = $row['group_id'] ?? 0;
        $ids=[];
        if ($group_id) {//角色组
            $ids = Staff::getGroupStaffIds($group_id);
        }
        if (isset($row['staff_id']) && $row['staff_id']) {
            $ids = $staff_id = $row['staff_id'];
        } else {
            $staff_id = '';
        }
        $where = ['order_date' => [
            'between',
            $betweentime
        ], 'check_status' => 2];
        if ($group_id || $staff_id) {
            $where['owner_staff_id'] = ['in', $ids];
        }
        //新增订单数
        $contracts = ContractModel::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();
        $select = [];
        foreach ($contracts as $v) {
            $select[$v['ctime']] = $v['c'];
        }
        $data=[];
        $time = $between[0];
        $toMonthTime = $between[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['date'][] = intval(date('m', $time)).'月份';
            $data['number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $where['order_date']=[
            'between',
            $lastbetweentime
        ];
        //新增订单数
        $lastcontracts = ContractModel::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();
        $lastselect = [];
        foreach ($lastcontracts as $v) {
            $lastselect[$v['ctime']] = $v['c'];
        }
        $time = $lastbetween[0];
        $toMonthTime = $lastbetween[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['last_number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $monthRatio=[];
        foreach ($data['number'] as $val) {
            $last_number = $last_number ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $last_number=$val;
            $monthRatio[]=$ratio;
        }
        $yearRatio=[];
        foreach ($data['number'] as $k=>$val) {
            $last_number = $data['last_number'][$k] ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $yearRatio[]=$ratio;
        }
        $data['year_ratio']=$yearRatio;
        $data['month_ratio']=$monthRatio;
        $data['title']='订单数量统计分析（按创建时间且审核通过统计）';
        $this->view->assign([
            'data' =>$data,
            'year' => $year,
            'staff_id' => $staff_id,
            'group_id' => $group_id,
            'type' => $type,
        ]);
        return $this->view->fetch();
    }

    /**
     * 订单金额统计
     */
    public function money()
    {
        $type=input('type','bar');//bar 柱状图 pie 饼状图
        $row = input('row/a');
        $year = $row['year'] ?? date('Y');
        $betweentime = [date('Y-m-d 00:00:00',strtotime($year . '-01-01')), date('Y-m-d 23:59:59',strtotime($year . '-12-31') + 86400 - 1)];
        $between = [strtotime($year . '-01-01'), strtotime($year . '-12-31') + 86400 - 1];
        $lastbetweentime = [date('Y-m-d 00:00:00',strtotime(($year-1) . '-01-01')), date('Y-m-d 23:59:59',strtotime(($year-1) . '-12-31') + 86400 - 1)];
        $lastbetween = [strtotime(($year-1) . '-01-01'), strtotime(($year-1) . '-12-31') + 86400 - 1];

        $group_id = $row['group_id'] ?? 0;
        $ids=[];
        if ($group_id) {//角色组
            $ids = Staff::getGroupStaffIds($group_id);
        }
        if (isset($row['staff_id']) && $row['staff_id']) {
            $ids = $staff_id = $row['staff_id'];
        } else {
            $staff_id = '';
        }
        $where = ['order_date' => [
            'between',
            $betweentime
        ], 'check_status' => 2];
        if ($group_id || $staff_id) {
            $where['owner_staff_id'] = ['in', $ids];
        }
        //新增订单数
        $contracts = ContractModel::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,sum(money) as money")->group('ctime')->select();
        $select = [];
        foreach ($contracts as $v) {
            $select[$v['ctime']] = $v['money'];
        }
        $data=[];
        $time = $between[0];
        $toMonthTime = $between[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['date'][] = intval(date('m', $time)).'月份';
            $data['number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $where['order_date']=[
            'between',
            $lastbetweentime
        ];
        //新增订单数
        $lastcontracts = ContractModel::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),'%Y-%m') as ctime,sum(money) as money")->group('ctime')->select();
        $lastselect = [];
        foreach ($lastcontracts as $v) {
            $lastselect[$v['ctime']] = $v['money'];
        }
        $time = $lastbetween[0];
        $toMonthTime = $lastbetween[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['last_number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $monthRatio=[];
        foreach ($data['number'] as $val) {
            $last_number = $last_number ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $last_number=$val;
            $monthRatio[]=$ratio;
        }
        $yearRatio=[];
        foreach ($data['number'] as $k=>$val) {
            $last_number = $data['last_number'][$k] ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $yearRatio[]=$ratio;
        }
        $data['year_ratio']=$yearRatio;
        $data['month_ratio']=$monthRatio;
        $data['title']='订单金额统计分析（按创建时间且审核通过统计）';
        $this->view->assign([
            'data' =>$data,
            'year' => $year,
            'staff_id' => $staff_id,
            'group_id' => $group_id,
            'type' => $type,
        ]);
        return $this->view->fetch();
    }
    /**
     * 回款金额统计
     */
    public function receivables()
    {
        $type=input('type','bar');//bar 柱状图 pie 饼状图
        $row = input('row/a');
        $year = $row['year'] ?? date('Y');
        $betweentime = [date('Y-m-d 00:00:00',strtotime($year . '-01-01')), date('Y-m-d 23:59:59',strtotime($year . '-12-31') + 86400 - 1)];
        $between = [strtotime($year . '-01-01'), strtotime($year . '-12-31') + 86400 - 1];
        $lastbetweentime = [date('Y-m-d 00:00:00',strtotime(($year-1) . '-01-01')), date('Y-m-d 23:59:59',strtotime(($year-1) . '-12-31') + 86400 - 1)];
        $lastbetween = [strtotime(($year-1) . '-01-01'), strtotime(($year-1) . '-12-31') + 86400 - 1];
        $group_id = $row['group_id'] ?? 0;
        $ids=[];
        if ($group_id) {//角色组
            $ids = Staff::getGroupStaffIds($group_id);
        }
        if (isset($row['staff_id']) && $row['staff_id']) {
            $ids = $staff_id = $row['staff_id'];
        } else {
            $staff_id = '';
        }
        $where = ['return_time' => [
            'between',
            $betweentime
        ], 'check_status' => 2];
        if ($group_id || $staff_id) {
            $where['owner_staff_id'] = ['in', $ids];
        }
        //
        $receivables = Receivables::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),'%Y-%m') as ctime,sum(money) as money")->group('ctime')->select();
        $select = [];
        foreach ($receivables as $v) {
            $select[$v['ctime']] = $v['money'];
        }
        $data=[];
        $time = $between[0];
        $toMonthTime = $between[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['date'][] = intval(date('m', $time)).'月份';
            $data['number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $where['return_time']=[
            'between',
            $lastbetweentime
        ];
        //
        $lastreceivables = Receivables::where($where)->field("FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),'%Y-%m') as ctime,sum(money) as money")->group('ctime')->select();
        $lastselect = [];
        foreach ($lastreceivables as $v) {
            $lastselect[$v['ctime']] = $v['money'];
        }
        $time = $lastbetween[0];
        $toMonthTime = $lastbetween[1];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $data['last_number'][] = $select[date('Y-m', $time)] ?? 0;
        }
        $monthRatio=[];
        foreach ($data['number'] as $val) {
            $last_number = $last_number ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $last_number=$val;
            $monthRatio[]=$ratio;
        }
        $yearRatio=[];
        foreach ($data['number'] as $k=>$val) {
            $last_number = $data['last_number'][$k] ?? 0;
            if(empty($val) && empty($last_number)){
                $ratio=0;
            }elseif(empty($val) && $last_number){
                $ratio=-100;
            }elseif(empty($last_number) && $val){
                $ratio=100;
            }else{
                if($last_number > $val){
                    $ratio=-(sprintf("%.2f", ($last_number-$val)/$last_number * 100));
                }else{
                    $ratio=(sprintf("%.2f", ($val-$last_number)/$last_number * 100));
                }
            }
            $yearRatio[]=$ratio;
        }
        $data['year_ratio']=$yearRatio;
        $data['month_ratio']=$monthRatio;
        $data['title']='回款金额统计分析（按创建时间且审核通过统计）';
        $this->view->assign([
            'data' =>$data,
            'year' => $year,
            'staff_id' => $staff_id,
            'group_id' => $group_id,
            'type' => $type,
        ]);
        return $this->view->fetch();
    }


}
